package com.huatai.common.interceptor;

import com.huatai.common.entity.AuthUserContext;
import com.huatai.common.entity.UserInfo;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.StringUtil;
import com.huatai.common.util.logUtil.SecurityConstants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: ganghua
 * @description: 用户登录解析
 * @author: songxiude
 * @create: 2024-09-24 19:34
 **/
public class UserAuthContextInterceptor implements AsyncHandlerInterceptor {
//public class UserAuthContextInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
		//判断当前拦截到的是Controller的方法还是其他资源
		if (!(handler instanceof HandlerMethod)) {
			//当前拦截到的不是动态方法，直接放行
			return true;
		}

		String token = request.getHeader(SecurityConstants.AUTHORIZATION_HEADER);
		if(StringUtil.isNoneBlank(token)){
			UserInfo user = AuthUtil.parseUser(token);
			AuthUserContext.setUser(user);
			//向下传递token
//			response.addHeader(SecurityConstants.AUTHORIZATION_HEADER,token);
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		AuthUserContext.clear();
	}

}
